// pages/profile/change-password.ts
import { MerchantAPI } from '../../utils/api'

Page({
  data: {
    statusBarHeight: 0,
    formData: {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    },
    showOldPassword: false,
    showNewPassword: false,
    showConfirmPassword: false
  },

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 0,
      showOldPassword: false,
      showNewPassword: false,
      showConfirmPassword: false
    });
    
    console.log('页面加载，密码显示状态:', this.data);
  },

  // 输入框变化
  onInputChange(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 切换密码可见性
  togglePasswordVisibility(e: any) {
    const field = e.currentTarget.dataset.field;
    const currentValue = this.data[field];
    
    console.log('切换密码可见性:', field, '当前值:', currentValue, '新值:', !currentValue);
    
    this.setData({
      [field]: !currentValue
    });
  },

  // 验证表单
  validateForm(): boolean {
    const { oldPassword, newPassword, confirmPassword } = this.data.formData;

    if (!oldPassword.trim()) {
      wx.showToast({
        title: '请输入原密码',
        icon: 'none'
      });
      return false;
    }

    if (!newPassword.trim()) {
      wx.showToast({
        title: '请输入新密码',
        icon: 'none'
      });
      return false;
    }

    // 验证密码长度
    if (newPassword.length < 6 || newPassword.length > 20) {
      wx.showToast({
        title: '密码长度为6-20位',
        icon: 'none'
      });
      return false;
    }

    if (!confirmPassword.trim()) {
      wx.showToast({
        title: '请确认新密码',
        icon: 'none'
      });
      return false;
    }

    // 验证两次密码是否一致
    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      });
      return false;
    }

    // 验证新旧密码不能相同
    if (oldPassword === newPassword) {
      wx.showToast({
        title: '新密码不能与原密码相同',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 提交修改密码
  async submitPassword() {
    if (!this.validateForm()) {
      return;
    }

    wx.showModal({
      title: '确认修改',
      content: '修改密码后需要重新登录，是否继续？',
      confirmText: '确认修改',
      confirmColor: '#5cb85c',
      success: async (res) => {
        if (res.confirm) {
          await this.doChangePassword();
        }
      }
    });
  },

  // 执行修改密码
  async doChangePassword() {
    wx.showLoading({
      title: '修改中...',
      mask: true
    });

    try {
      const response = await MerchantAPI.changePassword(this.data.formData);
      
      if (response.code === 200) {
        wx.hideLoading();
        
        wx.showModal({
          title: '修改成功',
          content: '密码已修改，请使用新密码重新登录',
          showCancel: false,
          confirmText: '重新登录',
          success: () => {
            // 清除登录信息
            wx.removeStorageSync('merchantToken');
            wx.removeStorageSync('merchantUserInfo');
            
            // 跳转到登录页
            wx.reLaunch({
              url: '/pages/auth/auth'
            });
          }
        });
      } else {
        wx.hideLoading();
        wx.showToast({
          title: response.msg || '修改失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      wx.hideLoading();
      console.error('修改密码失败:', error);
      
      // 处理错误信息
      let errorMsg = '修改失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.data && error.data.msg) {
        errorMsg = error.data.msg;
      }
      
      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 返回
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  }
});

